package com.cell.service.user.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cell.common.States;
import com.cell.common.exceptions.exceptions.PointAccountException;
import com.cell.common.exceptions.exceptions.UserException;
import com.cell.dao.user.UserDao;
import com.cell.pojo.DTO.user.loginaccount.loginByPasswordDTO;
import com.cell.pojo.DTO.user.loginaccount.validOldPasswordDTO;
import com.cell.pojo.DTO.user.validation.validateCodeDTO;
import com.cell.pojo.entity.user.User;
import com.cell.pojo.entity.user.UserLoginAccount;
import com.cell.dao.user.UserLoginAccountDao;
import com.cell.service.user.IUserLoginAccountService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cell.service.user.IUserValidationService;
import com.cell.utils.UserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author cloudJiang
 * @since 2022-06-04
 */
@Service
public class UserLoginAccountServiceImpl extends ServiceImpl<UserLoginAccountDao, UserLoginAccount> implements IUserLoginAccountService {
    @Autowired
    UserLoginAccountDao loginAccountDao;
    @Autowired
    UserDao userDao;
    @Autowired
    UserUtil util;
    @Autowired
    IUserValidationService validationService;


    @Override
    public User loginByPassword(loginByPasswordDTO loginByPasswordDTO) {
        QueryWrapper wrapper = new QueryWrapper();
        User user;


        //判断用户是否使用手机号登录
        if (util.isNumeric(loginByPasswordDTO.getLoginKey())) {
            wrapper.eq("phone", loginByPasswordDTO.getLoginKey());
        } else {
            wrapper.eq("email", loginByPasswordDTO.getLoginKey());
        }
        //由于邮箱和电话对于每个账户都是唯一的，故通过该值查找唯一对应的用户登录账户
        UserLoginAccount account = loginAccountDao.selectOne(wrapper);
        if (account != null) {
            //若账户存在，则查询密码是否一致。
            if (account.getPassword().equals(util.encryptByMD5(loginByPasswordDTO.getPassword()))) {
                //密码正确，则将用户对象存入session中
                wrapper.clear();
                //通过登录账户的id查询用户，并存入session
                wrapper.eq("login_account_id", account.getId());
                user = userDao.selectOne(wrapper);
                if (user == null) {
                    throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "用户不存在");
                }
            } else {
                throw new UserException(States.ERR_JWT_MALFORMED.getStates(), "密码错误");
            }
        } else {
            throw new UserException(States.ERR_USER_NOT_FOUND.getStates(), "用户不存在");
        }

        return user;
    }

    @Override
    public void validOldPassword(validOldPasswordDTO validOldPasswordDTO) {
        User user = userDao.selectById(validOldPasswordDTO.getUserId());
        UserLoginAccount loginAccount = loginAccountDao.selectById(user.getLoginAccountId());

        if (!loginAccount.getPassword().equals(util.encryptByMD5(validOldPasswordDTO.getPassword()))) {
            throw new UserException(States.ERR_JWT_MALFORMED.getStates(), "密码错误");
        }
    }

    @Override
    public User loginByValidCode(validateCodeDTO validateCodeDTO) {
        return validationService.validateCode(validateCodeDTO);
    }

    @Override
    public void resetPassword(String password, Long accountId) {
        UserLoginAccount loginAccount = this.getById(accountId);
        loginAccount.setPassword(util.encryptByMD5(password));
        this.updateById(loginAccount);
    }

    // TODO 逻辑优化
    @Override
    public void resetPhone(Long accountId, String phone) {
        UserLoginAccount loginAccount = loginAccountDao.selectById(accountId);
        //查找电话是否唯一
        QueryWrapper<UserLoginAccount> phonewrapper = new QueryWrapper<>();
        phonewrapper.eq("phone", phone);
        UserLoginAccount userLoginAccount1 = loginAccountDao.selectOne(phonewrapper);
        System.out.println(userLoginAccount1);
        if (userLoginAccount1 != null) {
            throw new UserException(States.ERR_SELECT.getStates(), "该电话号码已经被注册，请更换号码");
        }

        loginAccount.setPhone(phone);
        int i = loginAccountDao.updateById(loginAccount);
        if (i != 1) {
            throw new PointAccountException(States.ERR_UNIQUE.getDescription(), States.ERR_UNIQUE.getStates());
        }
    }

    @Override
    public void resetEmail(Long accountId, String email) {
        UserLoginAccount loginAccount = loginAccountDao.selectById(accountId);

        //查找邮箱是否唯一
        QueryWrapper<UserLoginAccount> wrapper = new QueryWrapper<>();
        wrapper.eq("email", email);
        UserLoginAccount userLoginAccount1 = loginAccountDao.selectOne(wrapper);
        System.out.println(userLoginAccount1);
        if (userLoginAccount1 != null) {
            throw new UserException(States.ERR_SELECT.getStates(), "该邮箱已经被注册，请更换号码");
        }

        loginAccount.setEmail(email);
        int i = loginAccountDao.updateById(loginAccount);
        if (i != 1) {
            throw new PointAccountException(States.ERR_UNIQUE.getDescription(), States.ERR_UNIQUE.getStates());
        }
    }

    @Override
    public String getTurePhone(Long accountId) {
        UserLoginAccount userLoginAccount = loginAccountDao.selectById(accountId);
        return userLoginAccount.getPhone();
    }

    @Override
    public String getPhone(Long accountId) {
        UserLoginAccount userLoginAccount = loginAccountDao.selectById(accountId);
        String phone = userLoginAccount.getPhone();
        String phoneResult = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return phoneResult;
    }

    @Override
    public String getEmail(Long accountId) {
        UserLoginAccount userLoginAccount = loginAccountDao.selectById(accountId);
        return userLoginAccount.getEmail();
    }


}
